import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Progress,
  Table,
  Select,
  DatePicker,
  Button,
  Typography,
  Tabs,
  Space,
  message,
  Tag,
  List,
} from 'antd';
import {
  BarChartOutlined,
  ArrowUpOutlined,
  DownloadOutlined,
  EyeOutlined,
  RiseOutlined,
  FallOutlined,
  FileTextOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;

// 数据接口定义
interface AnalyticsData {
  keyword: string;
  adoptionRate: number;
  impressions: number;
  clicks: number;
  conversions: number;
  trend: 'up' | 'down' | 'stable';
}

interface PerformanceMetrics {
  totalKeywords: number;
  averageAdoption: number;
  totalImpressions: number;
  totalClicks: number;
  ctr: number;
  conversionRate: number;
}

const Analytics: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(30, 'day'),
    dayjs(),
  ]);
  const [selectedPeriod, setSelectedPeriod] = useState('30days');
  const [metrics, setMetrics] = useState<PerformanceMetrics>({
    totalKeywords: 0,
    averageAdoption: 0,
    totalImpressions: 0,
    totalClicks: 0,
    ctr: 0,
    conversionRate: 0,
  });
  const [analyticsData, setAnalyticsData] = useState<AnalyticsData[]>([]);

  // 模拟数据
  const mockMetrics: PerformanceMetrics = {
    totalKeywords: 24,
    averageAdoption: 0.78,
    totalImpressions: 45620,
    totalClicks: 3847,
    ctr: 0.084,
    conversionRate: 0.156,
  };

  const mockAnalyticsData: AnalyticsData[] = [
    {
      keyword: 'AI智能优化',
      adoptionRate: 0.85,
      impressions: 8950,
      clicks: 756,
      conversions: 118,
      trend: 'up',
    },
    {
      keyword: '机器学习',
      adoptionRate: 0.72,
      impressions: 6420,
      clicks: 534,
      conversions: 89,
      trend: 'up',
    },
    {
      keyword: '深度学习算法',
      adoptionRate: 0.68,
      impressions: 4380,
      clicks: 367,
      conversions: 52,
      trend: 'stable',
    },
    {
      keyword: '数据分析平台',
      adoptionRate: 0.91,
      impressions: 7850,
      clicks: 692,
      conversions: 134,
      trend: 'up',
    },
    {
      keyword: '自然语言处理',
      adoptionRate: 0.64,
      impressions: 3920,
      clicks: 298,
      conversions: 38,
      trend: 'down',
    },
  ];

  useEffect(() => {
    loadAnalyticsData();
  }, [dateRange, selectedPeriod]);

  const loadAnalyticsData = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      setMetrics(mockMetrics);
      setAnalyticsData(mockAnalyticsData);
    } catch (error) {
      message.error('加载分析数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns: ColumnsType<AnalyticsData> = [
    {
      title: '关键词',
      dataIndex: 'keyword',
      key: 'keyword',
      width: 200,
      render: (text: string) => <Text strong>{text}</Text>,
    },
    {
      title: '采用率',
      dataIndex: 'adoptionRate',
      key: 'adoptionRate',
      width: 120,
      render: (rate: number) => (
        <div>
          <Progress
            percent={rate * 100}
            size="small"
            status={rate >= 0.8 ? 'success' : rate >= 0.6 ? 'active' : 'exception'}
            format={(percent) => `${percent?.toFixed(1)}%`}
          />
        </div>
      ),
      sorter: (a, b) => a.adoptionRate - b.adoptionRate,
    },
    {
      title: '展现量',
      dataIndex: 'impressions',
      key: 'impressions',
      width: 100,
      render: (value: number) => value.toLocaleString(),
      sorter: (a, b) => a.impressions - b.impressions,
    },
    {
      title: '点击量',
      dataIndex: 'clicks',
      key: 'clicks',
      width: 100,
      render: (value: number) => value.toLocaleString(),
      sorter: (a, b) => a.clicks - b.clicks,
    },
    {
      title: '转化次数',
      dataIndex: 'conversions',
      key: 'conversions',
      width: 100,
      render: (value: number) => value.toLocaleString(),
      sorter: (a, b) => a.conversions - b.conversions,
    },
    {
      title: '趋势',
      dataIndex: 'trend',
      key: 'trend',
      width: 80,
      render: (trend: string) => {
        if (trend === 'up') {
          return <Tag color="green" icon={<RiseOutlined />}>上升</Tag>;
        } else if (trend === 'down') {
          return <Tag color="red" icon={<FallOutlined />}>下降</Tag>;
        } else {
          return <Tag color="blue">稳定</Tag>;
        }
      },
    },
  ];

  const handleExportReport = () => {
    message.success('报告导出中，请稍等...');
    // 这里实现报告导出逻辑
  };

  const handlePeriodChange = (value: string) => {
    setSelectedPeriod(value);
    const now = dayjs();
    let start;
    
    switch (value) {
      case '7days':
        start = now.subtract(7, 'day');
        break;
      case '30days':
        start = now.subtract(30, 'day');
        break;
      case '90days':
        start = now.subtract(90, 'day');
        break;
      default:
        start = now.subtract(30, 'day');
    }
    
    setDateRange([start, now]);
  };

  // 洞察报告数据
  const insights = [
    {
      title: '采用率提升',
      description: '"AI智能优化"关键词采用率较上周提升12%',
      type: 'success',
      icon: <ArrowUpOutlined style={{ color: '#52c41a' }} />,
    },
    {
      title: '新兴趋势',
      description: '"数据分析平台"搜索量激增，建议加强相关内容投入',
      type: 'info',
      icon: <BarChartOutlined style={{ color: '#1890ff' }} />,
    },
    {
      title: '优化建议',
      description: '"自然语言处理"转化率偏低，建议优化内容质量',
      type: 'warning',
      icon: <FileTextOutlined style={{ color: '#fa8c16' }} />,
    },
  ];

  const tabItems = [
    {
      key: 'overview',
      label: '概览',
      children: (
        <div>
          {/* 核心指标 */}
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={24} sm={12} lg={4}>
              <Card>
                <Statistic
                  title="关键词总数"
                  value={metrics.totalKeywords}
                  prefix={<SearchOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={4}>
              <Card>
                <Statistic
                  title="平均采用率"
                  value={(metrics.averageAdoption * 100).toFixed(1)}
                  suffix="%"
                  valueStyle={{ color: metrics.averageAdoption >= 0.7 ? '#3f8600' : '#cf1322' }}
                  prefix={<ArrowUpOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={4}>
              <Card>
                <Statistic
                  title="总展现量"
                  value={metrics.totalImpressions}
                  prefix={<EyeOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={4}>
              <Card>
                <Statistic
                  title="总点击量"
                  value={metrics.totalClicks}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={4}>
              <Card>
                <Statistic
                  title="点击率"
                  value={(metrics.ctr * 100).toFixed(2)}
                  suffix="%"
                  valueStyle={{ color: metrics.ctr >= 0.08 ? '#3f8600' : '#cf1322' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={4}>
              <Card>
                <Statistic
                  title="转化率"
                  value={(metrics.conversionRate * 100).toFixed(2)}
                  suffix="%"
                  valueStyle={{ color: metrics.conversionRate >= 0.15 ? '#3f8600' : '#cf1322' }}
                />
              </Card>
            </Col>
          </Row>

          {/* 关键词表现表格 */}
          <Card title="关键词表现分析">
            <Table
              columns={columns}
              dataSource={analyticsData}
              rowKey="keyword"
              loading={loading}
              pagination={{
                pageSize: 10,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
              }}
            />
          </Card>
        </div>
      ),
    },
    {
      key: 'insights',
      label: '洞察报告',
      children: (
        <div>
          <Card title="智能洞察" style={{ marginBottom: 16 }}>
            <List
              itemLayout="horizontal"
              dataSource={insights}
              renderItem={(item) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={item.icon}
                    title={item.title}
                    description={item.description}
                  />
                </List.Item>
              )}
            />
          </Card>

          <Row gutter={16}>
            <Col xs={24} lg={12}>
              <Card title="采用率分布">
                <div style={{ textAlign: 'center', padding: '40px 0' }}>
                  <Progress
                    type="circle"
                    percent={metrics.averageAdoption * 100}
                    format={(percent) => `${percent?.toFixed(1)}%`}
                    width={120}
                    strokeColor={{
                      '0%': '#108ee9',
                      '100%': '#87d068',
                    }}
                  />
                  <div style={{ marginTop: 16 }}>
                    <Text>平均采用率</Text>
                  </div>
                </div>
              </Card>
            </Col>
            <Col xs={24} lg={12}>
              <Card title="表现评级">
                <div style={{ padding: '20px 0' }}>
                  <div style={{ marginBottom: 16 }}>
                    <Text>优秀 (≥80%):</Text>
                    <Text style={{ float: 'right', color: '#52c41a', fontWeight: 'bold' }}>
                      {analyticsData.filter(item => item.adoptionRate >= 0.8).length} 个
                    </Text>
                  </div>
                  <div style={{ marginBottom: 16 }}>
                    <Text>良好 (60-80%):</Text>
                    <Text style={{ float: 'right', color: '#1890ff', fontWeight: 'bold' }}>
                      {analyticsData.filter(item => item.adoptionRate >= 0.6 && item.adoptionRate < 0.8).length} 个
                    </Text>
                  </div>
                  <div>
                    <Text>需优化 (&lt;60%):</Text>
                    <Text style={{ float: 'right', color: '#ff4d4f', fontWeight: 'bold' }}>
                      {analyticsData.filter(item => item.adoptionRate < 0.6).length} 个
                    </Text>
                  </div>
                </div>
              </Card>
            </Col>
          </Row>
        </div>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={2}>监控分析</Title>
        <Space>
          <Select
            value={selectedPeriod}
            onChange={handlePeriodChange}
            style={{ width: 120 }}
          >
            <Option value="7days">近7天</Option>
            <Option value="30days">近30天</Option>
            <Option value="90days">近90天</Option>
          </Select>
          <RangePicker
            value={dateRange}
            onChange={(dates) => dates && setDateRange(dates as [dayjs.Dayjs, dayjs.Dayjs])}
          />
          <Button
            type="primary"
            icon={<DownloadOutlined />}
            onClick={handleExportReport}
          >
            导出报告
          </Button>
        </Space>
      </div>

      <Tabs
        items={tabItems}
        size="large"
      />
    </div>
  );
};

export default Analytics;